import type { Position } from '../types/vtuber';
import config from '../config/index';

function throttle(func: Function, delay: number = 100): Function {
  let lastTime = 0;
  return function (...args: any[]) {
    const currentTime = Date.now();
    if (currentTime - lastTime >= delay) {
      lastTime = currentTime;
      return func.apply(this, args);
    }
  };
}

function debounce(func: Function, delay: number): Function {
  let timeoutId: ReturnType<typeof setTimeout>;

  return function (...args: any[]) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
function sleep(time: number = 1000): Promise<void> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
    }, time);
  });
}

function errorReport(error: { name: string; message: string; stack: string }): void {
  if (!window?.ClientMonitor?.reportFrameErrors) {
    return;
  }
  window.ClientMonitor.reportFrameErrors(
    {
      category: 'js',
      grade: 'Error'
    },
    {
      name: error.name,
      message: error.message,
      stack: error.stack
    }
  );
}

function getDomain(url?: string): string {
  try {
    const hostname = url ? new URL(url).hostname : location.hostname;
    let _domain = '';
    const arr = hostname.split('.');
    const ipReg = /^[0-9]+$/;
    if (arr[0] === 'localhost' || ipReg.test(arr[0])) {
      _domain = '10jqka.com.cn';
      return _domain;
    } else {
      arr.length > 2 ? (_domain = arr.slice(1).join('.')) : (_domain = arr.join('.'));
      return _domain;
    }
  } catch (error) {
    errorReport({
      name: `获取域名的方法错误 ${error.name}`,
      message: error.message,
      stack: error.stack
    });
  }
}

function buildQueryString(params?: { [key: string]: string }): string {
  if (!params) {
    return '';
  }
  const queryString = Object.keys(params)
    .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
  return queryString;
}

function setPosition(position: Position, dom: HTMLElement) {
  Object.keys(position).forEach((key: keyof Position) => {
    if (position[key]) {
      dom.style[key] = position[key];
    }
  });
}

function sendStat(suffix: string) {
  window.TA && window.TA.log({ id: config.statId + suffix });
}

// 检查浏览器是否是 Chrome 49
function judgeChrome49(): boolean {
  const chromeVersion = /Chrome\/([0-9.]+)/.exec(navigator.userAgent);
  if (chromeVersion) {
    const versionNumber = parseInt(chromeVersion[1].split('.')[0]);
    return versionNumber === 49;
  }
  return false;
}

// 导出
export {
  throttle,
  debounce,
  sleep,
  errorReport,
  getDomain,
  buildQueryString,
  setPosition,
  sendStat,
  judgeChrome49
};
